package com.example.消息可靠性.消费方保证.拉消息模式;

import com.example.消息可靠性.发送方保证.发送方确认机制.ConfirmConfig;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.GetResponse;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class PullAckMessage {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/pullMsg")
    public void pullMsg() {
        //每条消息的唯一标志
        long deliveryTag = 0;
        Channel channel = rabbitTemplate.getConnectionFactory().createConnection().createChannel(false);
        try {
            GetResponse response = channel.basicGet(ConfirmConfig.CONFIRM_QUEUE, false);
            deliveryTag = response.getEnvelope().getDeliveryTag();
            String s = new String(response.getBody());
            System.out.println("s = " + s);
            //int i = 1 / 0;
            channel.basicAck(deliveryTag,false);
        } catch (IOException e) {
            try {
                channel.basicNack(deliveryTag,false,true);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }

        }

    }

}
